package com.ac.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

public class FileSetUtil {

    // 定义非法字符替换策略
    private static final String ILLEGAL_CHARACTERS_REGEX = "[\\\\/:*?\"<>.|]";
    private static final char REPLACEMENT_CHAR = '-';
    public static String resetFileName(String name,String path,MultipartFile image) throws IOException {
        System.out.println(path);

        // 生成新的文件名
    long timestamp = System.currentTimeMillis();
    Random random = new Random();
    int randomNumber = random.nextInt(1000); // 生成一个 0 到 999 之间的随机数

    // 构建新的文件名
    String newFileName = name + "_" + timestamp + "_" + randomNumber;
        File newFile = new File(path, newFileName+".png");
        try (InputStream is = image.getInputStream();
             FileOutputStream fos = new FileOutputStream(newFile)) {

            byte[] buffer = new byte[1024];
            int bytesRead;

            // 从源文件读取并写入目标文件
            while ((bytesRead = is.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

            System.out.println("文件保存成功: " + newFile.getAbsolutePath());
            return newFileName;
        } catch (IOException e) {
            throw new IOException("文件保存失败: " + e.getMessage(), e);
        }
}
    public static File saveFile(MultipartFile file, String path, String fileName) {        // 清理文件名中的非法字符
        String safeFileName = fileName.replaceAll(ILLEGAL_CHARACTERS_REGEX, String.valueOf(REPLACEMENT_CHAR));

        File newFile = new File(path, safeFileName+".png");
        File parentDir = newFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs(); // 创建所有必要的父目录
        }
        try (InputStream is = file.getInputStream();
             FileOutputStream fos = new FileOutputStream(newFile)) {

            byte[] buffer = new byte[1024];
            int bytesRead;

            // 从源文件读取并写入目标文件
            while ((bytesRead = is.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            return newFile;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
